package com.example.demo.intercepter;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.example.demo.auth.AuthService;
import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class AuthIntercepter implements HandlerInterceptor {
	private final static Logger log = LoggerFactory.getLogger(AuthIntercepter.class);
	
	@Autowired
	AuthService authService;
	
	@Autowired
	ObjectMapper mapper;

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws IOException {
		log.info("----------------签名鉴权拦截-------------------");
		String appid = req.getParameter("appid");
		String sign = req.getParameter("sign");
		String checkAuth = authService.checkSyncAuth(appid, sign, req);
		if (checkAuth != null) {
			res.setStatus(HttpStatus.OK.value());
			res.setHeader("Content-type", "text/html;charset=UTF-8");
			res.getWriter().print(checkAuth);//Res.Failure("req timeout, please try again")
			return false;
		}
		return true;
	}

}
